package com.keyholesoftware.trango.apt;

import java.util.Map;

import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedAnnotationTypes("com.keyholesoftware.trango.annotations.TrangoDataOnDemand")
public class TrangoDataHarnessProcessor extends TrangoAnnotationProcessor {

	protected static final String ENTITY_CLASS_ELEMENT = "entityClassElement";
	protected static final String ENTITY_METHOD_NAME = "entity";

	protected static final String SERVICE_CLASS_ELEMENT = "serviceClassElement";
	protected static final String SERVICE_METHOD_NAME = "service";

	@Override
	protected Map<String, Object> buildContext(RoundEnvironment roundEnvironment, TypeElement annotationElement, TypeElement classElement) {
		Map<String, Object> context = super.buildContext(roundEnvironment, annotationElement, classElement);
		flattenAnnotationToContext(DATA_HARNESS_ANNOTATION, classElement, annotationElement, context);
		// NOT PRETTY - BUT NOT SURE HOW ELSE TO MATCH
		String serviceClassName = context.get("service").toString().replace(".class", "");
		for (Element element : roundEnvironment.getRootElements()) {
			if (element.getKind().isClass()) {
				TypeElement typeElement = (TypeElement) element;
				if (typeElement.getQualifiedName().contentEquals(serviceClassName)) {
					TypeElement entityClassElement = typeElement;
					AnnotationMirror entityAnnotationMirror = getAnnotationMirror(SERVICE_ANNOTATION, typeElement);
					TypeElement entityAnnotationElement = (TypeElement) entityAnnotationMirror.getAnnotationType().asElement();
					flattenAnnotationToContext(SERVICE_ANNOTATION, entityClassElement, entityAnnotationElement, context);
				}
			}
		}
		String entityClassName = context.get("entity").toString().replace(".class", "");
		for (Element element : roundEnvironment.getRootElements()) {
			if (element.getKind().isClass()) {
				TypeElement typeElement = (TypeElement) element;
				if (typeElement.getQualifiedName().contentEquals(entityClassName)) {
					TypeElement entityClassElement = typeElement;
					AnnotationMirror entityAnnotationMirror = getAnnotationMirror(ENTITY_ANNOTATION, typeElement);
					TypeElement entityAnnotationElement = (TypeElement) entityAnnotationMirror.getAnnotationType().asElement();
					flattenAnnotationToContext(ENTITY_ANNOTATION, entityClassElement, entityAnnotationElement, context);
				}
			}
		}
		return context;
	}

	@Override
	protected String getTemplateName() {
		return "TrangoDataHarness.vm";
	}
}
